<?php
/**
 * Created by PhpStorm.
 * User: bzg
 * Date: 2019/12/2
 * Time: 16:56
 */

namespace App\Extend\SysExtend\Command;


use App\Extend\SysExtend\Helper;
use EasySwoole\EasySwoole\Command\CommandInterface;

/**
 * 生成控制器
 * Class Controller
 * @package App\Extend\SysExtend\Command
 */
class Model implements CommandInterface
{

    public function commandName(): string
    {
        // TODO: Implement commandName() method.
        return 'make:model';
    }

    public function exec(array $args): ?string
    {
        // 生成控制器，控制器目录App/HttpController, 参数就是控制器的路径和名称
        $base_path = EASYSWOOLE_ROOT . '/App/Model/';
        if(empty($args[0])) {
            return '<error> please input model file name';
        }
        // 判断文件是否存在
        if(is_file($base_path . $args[0] . '.php')) {
            return '<error> model already existed!';
        }

        // 分开路径和模型名
        $c_arr = explode('/', $args[0]);

        // 首字母大写
        foreach ($c_arr as &$v) {
            $v = ucfirst($v);
        }

        if(count($c_arr) == 1) {
            $dir = '';
            $file = $c_arr[0];
        }else{
            $file = array_pop($c_arr);
            $dir = implode('/',$c_arr);
        }

        // 创建文件夹
        if(!is_dir($base_path . $dir)) {
            mkdir($base_path . $dir, 0777, true);
        }

        // 组装命名空间
        $namespace = $dir ? '\\' . str_replace('/','\\', $dir) : '';

        // 生成表名 大驼峰转下划线
        $table = Helper::config('database.table_prefix') . ltrim(strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $file)),'_');


        // 写入文件
        $content = <<<EOF
<?php


namespace App\Model{%namespace%};



use App\Model\BaseModel;


class {%class_name%} extends BaseModel
{
    protected \$tableName = '{%table%}';
}
EOF;
        $content = str_replace('{%namespace%}', $namespace, $content);
        $content = str_replace('{%class_name%}', $file, $content);
        $content = str_replace('{%table%}', $table, $content);
        file_put_contents($base_path . $dir . '/' . $file . '.php', $content);
        return '<success> create model success!';
    }

    public function help(array $args): ?string
    {
        // TODO: Implement help() method.
        return 'auto create model';
    }
}